using System.Text.Json;
using CMS.Service;
using CMS.Web.Attributes;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CMS.Web.Controllers;

public class LoginController(IUserService userService) : Controller {
    // GET
    [DoNotCheckLogin]
    public async Task<IActionResult> Index(string? returnUrl) {
        if(!string.IsNullOrEmpty(returnUrl)) ViewBag.ReturnUrl = returnUrl;
        if (!string.IsNullOrEmpty(HttpContext.Session.GetString("user"))) return Redirect($"/Home/Index");
        string? uid;
        if (string.IsNullOrEmpty(uid = HttpContext.Request.Cookies["uid"])) return View();
        if (!int.TryParse(uid, out int id)) return View();
        var user = await userService.Get(u => u.Id == id).FirstOrDefaultAsync();
        HttpContext.Session.SetString("user", JsonSerializer.Serialize(user));
        return Redirect($"/Home/Index");
    }

    [HttpPost]
    [DoNotCheckLogin]
    public async Task<IActionResult> UserLogin(string username, string password, int? checkMe) {
        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) {
            return Json(new { code = 400, msg = "Username or password is empty." });
        }

        var user = await userService.Get(u => u.UserName == username && u.UserPassword == password)
                                    .FirstOrDefaultAsync();
        if (user == null) {
            return Json(new { code = 404, msg = "User not found." });
        }

        if (checkMe != null) {
            HttpContext.Response.Cookies.Append("uid", user.Id.ToString(), new CookieOptions() {
                Expires = DateTimeOffset.Now.AddDays(30)
            });
        }
        HttpContext.Session.SetString("user", JsonSerializer.Serialize(user));
        return Json(new { code = 200, msg = "Logged in." });
    }
}